package com.perfma.xtest.request;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

public class TextFileComparator {
    public static void main(String[] args) {
        String folder1Path = "/Users/sijunhui/Downloads/log/pid文件/29.16.16.243/simulations"; // 第一个文件夹的路径
        String folder2Path = "/Users/sijunhui/Downloads/log/pid文件/29.16.16.133/simulations"; // 第二个文件夹的路径

        compareFolders(folder1Path, folder2Path);
    }

    public static void compareFolders(String folder1Path, String folder2Path) {
        File folder1 = new File(folder1Path);
        File folder2 = new File(folder2Path);

        if (!folder1.isDirectory() || !folder2.isDirectory()) {
            System.out.println("指定的路径不是有效的文件夹路径。");
            return;
        }

        File[] files1 = folder1.listFiles();
        File[] files2 = folder2.listFiles();

        if (files1 == null || files2 == null) {
            System.out.println("无法读取文件夹中的文件。");
            return;
        }

        for (File file1 : files1) {
            if (file1.isFile()) {
                String fileName = file1.getName();
                File file2 = new File(folder2, fileName);

                if (file2.exists() && file2.isFile()) {
                    try {
                        if (areFilesEqual(file1.toPath(), file2.toPath())) {
                            System.out.println(fileName + " 的内容相同。");
                        } else {
                            System.out.println(fileName + " 的内容不同。");
                        }
                    } catch (IOException e) {
                        System.out.println("比较文件时发生错误：" + e.getMessage());
                    }
                } else {
                    System.out.println("文件 " + fileName + " 在第二个文件夹中不存在。");
                }
            }
        }
    }

    public static boolean areFilesEqual(Path path1, Path path2) throws IOException {
        long fileSize1 = Files.size(path1);
        long fileSize2 = Files.size(path2);

        if (fileSize1 != fileSize2) {
            return false;
        }

        try (FileInputStream fis1 = new FileInputStream(path1.toFile());
             FileInputStream fis2 = new FileInputStream(path2.toFile())) {
            byte[] buffer1 = new byte[8192];
            byte[] buffer2 = new byte[8192];
            int bytesRead1;
            int bytesRead2;

            while ((bytesRead1 = fis1.read(buffer1)) != -1) {
                bytesRead2 = fis2.read(buffer2);

                if (bytesRead1 != bytesRead2 || !Arrays.equals(buffer1, buffer2)) {
                    return false;
                }
            }
        }

        return true;
    }
}